package com.atguigu.gulimall.auth.controller;

import com.atguigu.common.constant.SmsConstant;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.auth.feign.SmsFeignService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/sms")
public class SmsController {
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private SmsFeignService smsFeignService;

    @GetMapping("/sendCode")
    public R sendCode(String phone){
        if(StringUtils.isEmpty(phone)){
            return R.error();
        }
        String c = redisTemplate.opsForValue().get(SmsConstant.SMS_CODE_PREFIX + phone);
        if(StringUtils.isNotEmpty(c)){
            long l = Long.parseLong(c.split("_")[1]);
            if((System.currentTimeMillis()-l)<60000){
                return R.error();
            }
        }
        //生产随机验证码
        String code = UUID.randomUUID().toString().substring(0, 4)+"_"+System.currentTimeMillis();

        //存入redis
        redisTemplate.opsForValue().set(SmsConstant.SMS_CODE_PREFIX+phone,code,10, TimeUnit.MINUTES);

        //调用三方服务发送短信
        smsFeignService.sendMsg(phone,code.split("_")[0]);
        return R.ok();
    }
}